<?php

namespace common\models;

use Yii;

/**
 * 项目尽调报告-债权基本情况
 * This is the model class for table "project_investigation".
 *
 * @property string $id
 * @property string $project_id
 * @property string $borrower
 * @property string $guarantor
 * @property string $mortgagor
 * @property string $mortgage_type
 * @property string $principal
 * @property string $interest
 * @property string $lawsuit
 * @property string $execution
 * @property string $auction
 * @property string $records_investigation
 * @property string $records_consistence
 * @property string $order_sent
 * @property string $court_summons
 * @property string $execution_method
 * @property string $layer_interview
 * @property string $debt_collection
 * @property string $prescription
 * @property string $origin_files
 * @property string $conclusion
 * @property string $created_at
 * @property string $updated_at
 * @property integer $lock_user
 * @property string $lock_timestamp
 */
class ProjectInvestigation extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'project_investigation';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['borrower', 'guarantor', 'mortgagor'], 'filter', 'filter' => 'trim'],
            //[['project_id', 'borrower', 'guarantor', 'mortgagor', 'mortgage_type', 'principal', 'interest'], 'required'],
            [['project_id', 'lock_user'], 'integer'],
            [['lawsuit', 'execution', 'auction', 'records_investigation', 'records_consistence', 'order_sent', 'court_summons', 'execution_method', 'layer_interview', 'debt_collection', 'prescription', 'origin_files', 'conclusion'], 'string'],
            [['created_at', 'updated_at'], 'safe'],
            [['borrower', 'guarantor', 'mortgagor', 'mortgage_type', 'principal', 'interest', 'lock_timestamp'], 'string', 'max' => 255],
            [['project_id'], 'unique'],
            ['mortgage_type', 'in', 'range' => [1, 2, 3, 4, 5, 6, 7, 8, 9]],
            ['principal', 'validatePrincipal'],
            ['interest', 'validateInterest'],
        ];
    }

    public function validatePrincipal()
    {
        if (!is_numeric($this->principal) && $this->principal !='' ) {
            $number = Package::set_number_format($this->principal);
            if ($this->principal != $number) {
                $this->addError('principal', '本金格式不正确。');
            }
        }
    }

    public function validateInterest()
    {
        if (!is_numeric($this->interest) && $this->interest !='' ) {
            $number = Package::set_number_format($this->interest);
            if ($this->interest != $number) {
                $this->addError('interest', '利息格式不正确。');
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'project_id' => '项目ID',
            'borrower' => '借款人',
            'guarantor' => '保证人',
            'mortgagor' => '抵押人',
            'mortgage_type' => '抵押物类型',
            'principal' => '本金',
            'interest' => '利息',
            'lawsuit' => '诉讼情况',
            'execution' => '执行情况',
            'auction' => '评估拍卖情况',
            'records_investigation' => '案卷查询情况',
            'records_consistence' => '案卷是否一致',
            'order_sent' => '调解书/支付令是否送达',
            'court_summons' => '开庭传票是否送达',
            'execution_method' => '执行终结方式',
            'layer_interview' => '法官/律师访谈',
            'debt_collection' => '未诉债权催收情况',
            'prescription' => '时效结论',
            'origin_files' => '证据是否有原件',
            'conclusion' => '结论',
            'created_at' => '创建时间',
            'updated_at' => '修改时间',
            'lock_user' => '上锁用户',
            'lock_timestamp' => '上锁时间',
        ];
    }


    /**
     *
     * @param bool $insert
     */
//    public function beforeSave($insert)
//    {
//        // TODO: Change the autogenerated stub
//        if (parent::beforeSave($insert)) {
//            if ($this->isNewRecord) {
//                $this->created_at = date('Y-m-d H:i:s', time());
//            } else {
//                $this->updated_at = date('Y-m-d H:i:s', time());
//            }
//            return true;
//        } else {
//            return false;
//        }
//    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub

        //项目
        $project = Project::findOne($this->project_id);

        if ($insert) {
            //添加操作日志
            $projectLog = new ProjectLog();
            $projectLog->project_id = $this->project_id;
            $projectLog->created_at = date('Y-m-d H:i:s', time());
            $projectLog->user_id = Yii::$app->user->id;
            $projectLog->log = '添加项目【'.  $project->title .'】尽调债权基本情况';
            $projectLog->save();
        }
    }

    /**
     * @param $id 主键
     * @param $project_id 项目id
     * @param $changedAttributes 属性值
     * @param $userId 用户id
     * @param $module 项目修改日志module
     * @param $module_type 项目类型 1混合类，2抵押类
     * @param int $type 1为添加,2为修改，3为删除
     * @return array
     */
    public function setUpdateLog($id, $project_id, $changedAttributes, $userId, $module/*, $module_type*/, $type)
    {
        $model = self::findOne((int)$id);
        $project = Project::findOne($project_id);
        if ($model === null || $project === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }

        if ($project->type != 2 ) {
            $project->type = 1;
        }

        $attributeLabels = $this->attributeLabels();
        $intAttributeLabels = ['project_id', 'mortgage_type', 'lock_user'];
        $userInfo = (new UserModel())->getDepartmentUsersList();

        switch ($type) {
            //添加
            case 1:
                $data = $changedAttributes;
                if (!empty($data)) {
                    $log = '新增';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'project_id':
                                    $value = $project->title;
                                    break;
                                case 'mortgage_type':
                                    if (strlen(trim($value,',')) >0 ) {
                                        $title = Yii::$app->params['InvestigationMortgageType'];
                                        $arr = explode(',', trim($value, ','));
                                        $str = '';
                                        foreach ($arr as $v) {
                                            if (is_numeric($v)) {
                                                $str .= $title[(int)$v] . '，';
                                            }
                                        }
                                        $value = mb_substr($str, 0, -1, 'utf-8');
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'lock_user':
                                    if ($value>0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                default:
                            }
                        }
                        if ($attributeLabels[$key] != 'ID') {
                            $log .= "{$attributeLabels[$key]}：{$value}\n";
                        }
                    }
                }
                break;

            //编辑
            case 2:
                //判断数据是否发生改变
                $state = false;
                $data = array(); //修改后的数据
                foreach ($changedAttributes as $key => $value) {
                    if ($model->$key != $value) {
                        $data[$key] = $value;
                        $state = true;
                    }
                }

                if (!$state) {
                    $model->lock_user = null;
                    $model->lock_timestamp = null;
                    if ($model->save()) {
                        return array('state' => true, 'msg' => '保存成功');
                    } else {
                        return array('state' => false, 'msg' => '保存失败');
                    }
                    //return array('state' => false, 'msg' => '没有做任何修改');
                }

                if (!empty($data)) {
                    $log = '';
                    //$log = '修改ID：' . $id . ',';
                    //$log = '修改ID为' . $id . '的立项信息数据,';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'project_id':
                                    $value = $project->title;
                                    break;
                                case 'mortgage_type':
                                    if (strlen(trim($value,',')) >0 ) {
                                        $title = Yii::$app->params['InvestigationMortgageType'];
                                        $arr = explode(',', trim($value, ','));
                                        $str = '';
                                        foreach ($arr as $v) {
                                            if (is_numeric($v)) {
                                                $str .= $title[(int)$v] . '，';
                                            }
                                        }
                                        $value = mb_substr($str, 0, -1, 'utf-8');
                                    } else {
                                        $value = '';
                                    }
                                    break;
                                case 'lock_user':
                                    if ($value>0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                default;
                            }
                        }
                        $log .= "{$attributeLabels[$key]}：{$value}\n";
                    }
                }
                break;

            //删除
            case 3:
                //$log = "删除ID：{$id}，";
                $log = "删除记录，";
                break;
            default:
        }

        try {
            $time = date('Y-m-d H:i:s');
            $projectUpdateLog = new ProjectUpdateLog();
            if ($project->type !=2 ) {
                $project->type = 1;
            }
            $module_title_array = $projectUpdateLog->getModuleArrayTitle($project->type);
            $projectUpdateLog->project_id = $project_id;
            $projectUpdateLog->module = $module_title_array[$module];
            $projectUpdateLog->type = $project->type;
            $projectUpdateLog->created_at = $time;
            $projectUpdateLog->user_id = $userId;
            $projectUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');
            $re1 = $projectUpdateLog->save();
            if (!$re1) {
                throw new \Exception('项目尽调日志添加失败');
            }

            return array('state' => true, 'msg' => '添加项目尽调修改日志成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }

}
